package com.woniuxy.controller;

import com.woniuxy.entity.User;
import com.woniuxy.service.UserService;
import com.woniuxy.utils.JWTUtil;
import com.woniuxy.utils.ResponseResults;
import com.woniuxy.utils.ResponseState;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;


@Slf4j
//@RestController
//@RequestMapping("/user")
public class UserController {

    @Resource
    UserService userService;

    @PostMapping("/login")
    public ResponseResults<User> login(@RequestBody User user, HttpServletResponse response){
        User loginUser = userService.getLoginUser(user.getAccount());
        /**
         * 判空，判用户名和密码与数据库是否一致
         * */
        if (loginUser!=null){
            // 判用户名、密码
            if (loginUser.getAccount().equals(user.getAccount()) && loginUser.getPassword().equals(user.getPassword())){
                // 登录成功
                // 生成令牌
                String token = JWTUtil.generateToken(loginUser.getId());
                // 将token放入响应头
                response.setHeader("authorization",token);
                /**
                 * 自定义的响应头必须要暴露给前端，告知前端这个header没有问题
                 * 自定义头一定要保持一致
                 * Access-Control-Expose-Headers 是固定的
                 * */
                response.setHeader("Access-Control-Expose-Headers","authorization");
                return new ResponseResults<User>()
                        .setMsg("登录成功")
                        .setCode(200)
                        .setState(ResponseState.LOGIN_SUCCESS)
                        .setData(loginUser);
            }else {
                System.out.println("用户名或密码错误，请重新登录");
                return new ResponseResults<User>()
                        .setMsg("用户名或密码错误，请重新登录!")
                        .setCode(500)
                        .setState(ResponseState.NO_LOGIN)
                        .setData(null);
            }
        } else {
            System.out.println("该用户不存在!");
            return new ResponseResults<User>()
                    .setMsg("用户不存在，请重新登录")
                    .setCode(500)
                    .setState(ResponseState.NO_LOGIN)
                    .setData(null);
        }
    }
}
